/** Copyright (C) 2010  Expertise Android

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    */

package com.gangwangchina.android.contactlib.utils;

import android.database.Cursor;
import android.database.MatrixCursor;
import android.provider.ContactsContract.Data;

public class CursorUtils {
	
	/**
	 * Makes an intersection between cursors
	 * @param cursors the array of cursors that should be intersected
	 * @return the intersection of the cursors
	 */
	public static Cursor intersect(Cursor[] cursors){
		if(cursors.length<1) return null;
		if(cursors.length==1) return cursors[0];
		Cursor mix = cursors[0];
		for(int i=1; i<cursors.length;i++){
			mix = intersect(mix, cursors[i]);
		}
		return mix;
	}
	
	/**
	 * Pre-requesite : cursors should be sorted
	 * Complexity : O(n)
	 * @param left
	 * @param right
	 * @return an intersection of the cursors
	 */
	public static Cursor intersect(Cursor left, Cursor right){
		String[] resColumns = { Data.CONTACT_ID, Data.DISPLAY_NAME};
		MatrixCursor cursor = new MatrixCursor(resColumns);
		left.moveToFirst();
		right.moveToFirst();
		long l,r;
		
		while(!(left.isAfterLast()||right.isAfterLast())){
			l = left.getLong(0);
			r = right.getLong(0);
			if(l==r){
				cursor.addRow(new Object[]{l, left.getString(1)});
				left.moveToNext();
				right.moveToNext();
			}
			else if (l<r) left.moveToNext();
			else if (l>r) right.moveToNext();
		}
		
		left.close();
		right.close();
		return cursor;
	}
}
